package agh.tk.markuptranslation;

import agh.tk.markuptranslation.AbstractWikiList.ListType;

public class OrderedList extends AbstractWikiList
{	
	/**
	 * 
	 * @param left 
	 * @param right
	 */
	public OrderedList(IComponent left, IComponent right) 
	{
		super(left, right);	
	}

	@Override
	public String toDokuWiki() 
	{
		if(leftChild == null)
			return "\n" ;
		StringBuilder stringBuilder = new StringBuilder(super.toDokuWiki());
		stringBuilder.append("-") ;
		if(leftChild != null)
			stringBuilder.append(leftChild.toDokuWiki()) ;
		if(rightChild != null)
			stringBuilder.append(rightChild.toDokuWiki()) ;
		return stringBuilder.toString();
	}

	@Override
	public String toMediaWiki() {
		if(leftChild == null)
			return "\n" ;
		StringBuilder result = new StringBuilder(super.toMediaWiki());
		for(int i=0; i<level; i++)
			result.append('#');
		result.append(leftChild.toMediaWiki());
		if(rightChild != null)
			result.append(rightChild.toMediaWiki());
		return result.toString();
	}
	
	@Override
	public String toHTML() {
		boolean addEndingTag = false;
		boolean alreadyAddedRightChild = false;
		if(leftChild == null)
			return "";
		StringBuilder result = new StringBuilder();
		if(currentListDepth > level) {
			currentListDepth = level;
			result.append(super.toHTML());
			if(tagsToClose.removeLast() == ListType.UNORDERED) {
				result.append("</ul>");
				result.append("</li>");
			}
			else {
				result.append("</ol>");
				result.append("</li>");
			}
		}
		if(OrderedList.currentListDepth < level) {
			currentListDepth = level;
			result.append(super.toHTML());
			result.append("<ol>");
			tagsToClose.addLast(ListType.ORDERED);
			addEndingTag = true;
		}
		result.append(super.toHTML());
		result.append(" ");
		result.append("<li>");
		result.append(leftChild.toHTML());
		if(rightChild!=null && rightChild instanceof AbstractWikiList && ((AbstractWikiList)rightChild).level > level) {
			alreadyAddedRightChild = true;
			result.append(rightChild.toHTML());
		} else {
		result.append("</li>");
		}
		if(rightChild!=null && !alreadyAddedRightChild)
			result.append(rightChild.toHTML());
		if(currentListDepth == 1 && addEndingTag) {
			currentListDepth = 0;
			result.append(super.toHTML());
			if(tagsToClose.removeLast() == ListType.UNORDERED)
				result.append("</ul>");
			else
				result.append("</ol>");
		}
		return result.toString();
	}

	@Override
	public String toTxt2tags() 
	{
		StringBuilder stringBuilder = new StringBuilder(super.toTxt2tags());
		stringBuilder.append("+") ;
		if(leftChild == null)
			stringBuilder.append("\n") ;
		else
			stringBuilder.append(leftChild.toTxt2tags()) ;
		if(rightChild != null)
			stringBuilder.append(rightChild.toTxt2tags()) ;
		return stringBuilder.toString();
	}
}
